import { lazyReport } from "./report.js";
import { getCurrentTime } from "./utils.js";
import { PAGE } from "./constants.js";
let beforeTime = Date.now();
let beforePage = window.location.href;

const getStayTime = () => {
  const nowTime = Date.now();
  const stayTime = nowTime - beforeTime;
  const startTime = getCurrentTime(beforeTime);
  const endTime = getCurrentTime();
  beforeTime = nowTime;
  return { startTime, endTime, stayTime };
};
const listener = () => {
  const { startTime, endTime, stayTime } = getStayTime();
  const currentPage = window.location.href;
  lazyReport({
    type: PAGE,
    data: { startTime, endTime, stayTime, currentPage },
  });
  beforePage = currentPage;
};
// history模式下pushState和replaceState方法不会触发popState事件,故需重写
const createTypeEvent = (name) => {
  const origin = window.history[name];
  return function (event) {
    const result = origin.apply(this, arguments);
    let e = new Event(name);
    e.arguments = arguments;
    window.dispatchEvent(e);
    return result;
  };
};
/**
 * history路由监听
 */
export const historyPageTracker = () => {
  window.history.pushState = createTypeEvent("pushState");
  window.history.replaceState = createTypeEvent("replaceState");
  window.addEventListener("pushState", () => {
    listener();
  });
  window.addEventListener("replaceState", () => {
    listener();
  });
  // 用来监听go()、back()、forward()
  window.addEventListener("popstate", () => {
    listener();
  });
  // window.addEventListener("load", () => {
  //   listener();
  // });
  window.addEventListener("unload", () => {
    listener();
  });
};

/**
 * hash路由监听
 */
export const hashPageTracker = () => {
  window.history.pushState = createTypeEvent("pushState");
  window.addEventListener("pushState", () => {
    listener();
  });
  window.addEventListener("hashchange", () => {
    listener();
  });
  // window.addEventListener("load", () => {
  //   listener();
  // });
  window.addEventListener("unload", () => {
    listener();
  });
};
export default { historyPageTracker, hashPageTracker };
